#include "esp_camera.h"
#include <WiFiManager.h>
#include <Adafruit_NeoPixel.h>
#include "camera_pins.h"

#define LED_PIN                 48
#define LED_COUNT               1
#define WIFI_CONFIG_BUTTON_PIN  0

Adafruit_NeoPixel pixels(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
volatile bool should_blink_blue = false;
WiFiClient espClient;
volatile bool wifi_connect_success = false;

void cameraInit(volatile bool *wifi_connect_success);
void startCameraServer();
void stopCameraServer();

void rgbBlinkColor(unsigned int r = 0, unsigned int g = 0, unsigned b = 0)
{
  pixels.setPixelColor(0, pixels.Color(r, g, b));
  pixels.show();
  vTaskDelay(pdMS_TO_TICKS(100));
  pixels.clear();
  pixels.show();
}

void startWiFiConfig()
{
  should_blink_blue = true;

  WiFiManager wm;
  wm.setConfigPortalBlocking(true);
  wm.setConfigPortalTimeout(300);

  Serial.println("WiFi手动配网");
  Serial.println("请连接热点: wifi_config");

  if (!wm.startConfigPortal("wifi_config")) {
    Serial.println("WiFi配网超时, 即将重启!");
    vTaskDelay(pdMS_TO_TICKS(1000));
    ESP.restart();
  }

  should_blink_blue = false;
  vTaskDelay(pdMS_TO_TICKS(100));
}

void blinkBlueBreathingTask(void *param)
{
  while (1) {
    if (should_blink_blue) {
      rgbBlinkColor(0, 0, 255);
    }
    vTaskDelay(pdMS_TO_TICKS(1000));
  }
}

void wifiTask(void *param)
{
  WiFi.mode(WIFI_STA);
  WiFi.begin();
  unsigned int count = 10;
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 10000) {
    Serial.println(("WiFi自动连接中..." + String(count) + "s").c_str());
    vTaskDelay(pdMS_TO_TICKS(1000));
    count--;
  }
  if (WiFi.status() != WL_CONNECTED) startWiFiConfig();
  Serial.println("WiFi已连接!");
  vTaskDelay(pdMS_TO_TICKS(1000));
  wifi_connect_success = true;

  while (1) {
    if (digitalRead(WIFI_CONFIG_BUTTON_PIN) == LOW && should_blink_blue == false) {
      vTaskDelay(pdMS_TO_TICKS(50));
      if (digitalRead(WIFI_CONFIG_BUTTON_PIN) == LOW && should_blink_blue == false) {
        digitalWrite(2, LOW);
        stopCameraServer();
        startWiFiConfig();
        startCameraServer();
        digitalWrite(2, HIGH);
      }
    }
    vTaskDelay(pdMS_TO_TICKS(100));
  }
}

void setup()
{
  Serial.begin(115200);
  pinMode(WIFI_CONFIG_BUTTON_PIN, INPUT_PULLUP);
  pinMode(2, OUTPUT);
  pixels.begin();
  pixels.clear();
  pixels.show();
  Serial.println("系统启动中...");

  xTaskCreatePinnedToCore(blinkBlueBreathingTask, "blinkBlue", 2048, NULL, 2, NULL, 1);
  xTaskCreatePinnedToCore(wifiTask, "wifiTask", 16384, NULL, 1, NULL, 1);

  cameraInit(&wifi_connect_success);
  startCameraServer();
  Serial.println("摄像头初始化成功！请访问 http://" + WiFi.localIP().toString());
  digitalWrite(2, HIGH);
}

void loop() {}

